import Vue from "vue";
import config from "../config";

function getStoraged(key) {
  const data = uni.getStorageSync(key);
  if (data) {
    return data;
  } else {
    return "";
  }
}
// 设置公共路径
// const baseUrl = config.baseUrl;
const baseUrl = config.baseUrl;

// 同步请求
const request = (url, data, method, callback, hideLoading) => {
  const headers = {
    // "content-type": "application/json",
    "content-type": "application/json;charset=utf-8",
    "x-requested-with": "XMLHttpRequest",
    'cache-control': 'no-cache',
    'Access-Control-Allow-Headers': 'appId',
    'Access-Control-Allow-Methods': 'POST,GET,OPTIONS',
    'Access-Control-Max-Age': 86400,
  };
  // 如果调用接口不明确不显示 loading
  if (!hideLoading) {
    uni.showLoading({
      title: "加载中",
    });
  }

  uni.request({
    //#ifdef MP-WEIXIN
    url: url.substr(0, 4) == "http" ? url : baseUrl + url,
    //#endif
    //#ifdef H5 || APP-PLUS
    url: url,
    //#endif
    data: data,
    header: headers,
    method: method,
    withCredentials: true,
    success: response => {
      if (!hideLoading) {
        uni.hideLoading();
      }

      const result = response.data;
      if (response.statusCode == 200) {
        const head = response.header;
        if (head.is_login === "0" && head.redirect_url) {
          if (process.env.NODE_ENV === "production") window.location.href = head.redirect_url;
        } else if (head.is_granted === "0") {
          uni.showToast({
            icon: "none",
            title: "暂无权限，请先开通权限",
          });
        } else {
          callback(result);
        }
      } else {
        showError(response);
      }
    },
    complete: () => {
      if (!hideLoading) {
        uni.hideLoading();
      }
    },
    fail: () => {
      if (!hideLoading) {
        uni.hideLoading();
      }
      uni.showToast({
        title: "请求失败，请重试",
        icon: "none",
        duration: 1500,
      });
    },
  });
};
// 异步请求
const requestSync = (
  url = "",
  data = {},
  type = "POST",
  header = {
    "content-type": "application/json;charset=utf-8",
    'cache-control': 'no-cache',
    'Access-Control-Allow-Headers': 'appId',
    'Access-Control-Allow-Methods': 'POST,GET,OPTIONS',
    'Access-Control-Max-Age': 86400,
  }
) => {
  return new Promise((resolve, reject) => {
    header.authration_token = getStoraged("authration_token") ? getStoraged("authration_token") : "";
    header.user_id = getStoraged("user_id");

    uni
      .request({
        method: type,
        //#ifdef MP-WEIXIN
        url: baseUrl + url, //微信中的请求路径
        //#endif
        //#ifdef H5 || APP-PLUS
        url: url, //H5中的请求路径
        //#endif
        data: data,
        header: header,
        // dataType: "json",
      })
      .then(response => {
        let codeResolve = [200, 10009, 10010, 10005, 10007]
        setTimeout(function () {
          uni.hideLoading();
        }, 200);
        let [error, res] = response;
        if (res.statusCode == 200) {
          resolve(res.data);
        } else if (res.statusCode == 403) {
          let arr = ["/user/status", "/collects/set"]
          if (!arr.includes(url)) {
            uni.showToast({
              title: "当前操作需要登录",
              icon: "none",
              duration: 2000,
              success: () => {
                setTimeout(() => {
                  uni.navigateTo({
                    url: "/pages2/login",
                  });
                }, 2000);
              },
            });
          }
        }
      })
      .catch(error => {
        let [err, res] = error;
        reject(err);
      });
  });
};
// 展示服务端错误
const showError = error => {
  let errorMsg = "";
  switch (error.statusCode) {
    case 400:
      errorMsg = "请求参数错误";
      break;
    case 401:
      errorMsg = "未授权，请登录";
      break;
    case 403:
      errorMsg = "未登录";
      break;
    case 404:
      errorMsg = "请求地址出错";
      break;
    case 408:
      errorMsg = "请求超时";
      break;
    case 500:
      errorMsg = "服务器内部错误";
      break;
    case 501:
      errorMsg = "服务未实现";
      break;
    case 502:
      errorMsg = "网关错误";
      break;
    case 503:
      errorMsg = "服务不可用";
      break;
    case 504:
      errorMsg = "网关超时";
      break;
    case 505:
      errorMsg = "HTTP版本不受支持";
      break;
    default:
      errorMsg = error.msg;
      break;
  }

  uni.showToast({
    title: errorMsg,
    icon: "none",
    duration: 2000,
    complete: function () {
      setTimeout(function () {
        uni.hideToast();
      }, 1000);
    },
  });
};

const upload = file => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      //#ifdef MP-WEIXIN
      url: config.baseUrl + "/upload/img", //微信中的请求路径
      //#endif
      //#ifdef H5 || APP-PLUS
      url: "/upload/img", //H5中的请求路径
      //#endif
      filePath: file.url,
      count: 1,
      sizeType: ["original"], //可以指定是原图还是压缩图，默认二者都有  "compressed"
      // sourceType: ['camera','album'], //拍照或者从相册选择
      header: {
        user_id: getStoraged("user_id"),
        authration_token: getStoraged("authration_token") && getStoraged("authration_token"),
      },
      name: "file",
      formData: {
        file: file,
      },
      success: uploadFileRes => {
        resolve(uploadFileRes.data);
      },
    });
  });
};
Vue.prototype.$http = {
  request,
  showError,
  requestSync,
  upload
};